<?php

class PageController extends BackOfficeController
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';
    
    private $_activePages=array();

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
        $this->actionUpdate();
	}

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate()
    {
        $pageRevision = null;
        $pageUrls = array();
        if (Yii::app()->request->IsPostRequest) {
            // save posted data
            $_POST['validateOnly'] = ($this->post('ajax','') == 'page-form');
            $result = FSM::run('Cms.Page.saveDetails', $_POST);
            $model = $result->model; 
            /*$pageUrls = $result->pageUrls;
            Yii::trace(CVarDumper::dumpAsString($pageUrls), 'PageUrl');*/

            if ($this->post('ajax','') == 'page-form'){
                echo $result->getActiveErrorMessages($result->model);
                Yii::app()->end();
            }
            if (! $result->hasErrors()) {
                $this->message = Yii::t('Core','Item has been saved successfully.');
                if (Yii::app()->request->getIsAjaxRequest())
                {
                    echo CJSON::encode(array('id' => $model->id));
                    Yii::app()->end();
                }
                else
                {
		if ($result->newModel == 1) {
                    //auto add widget for page is flash content
                    if (Yii::app()->request->getParam('page_type', '') == 'flash_content' && (($markup = CmsWidget::model()->find("path = 'Cms.components.widgets.MarkupCode'")) != null))
                    {
                        $text = new Text;
                        $text->content = '<div>Click here to start adding content</div>';
                        $text->status = true;
                        $text->mime = 'text/html';
                        if (!$text->save())
                        {
                            Yii::log(CVarDumper::dumpAsString($text->getErrors()), CLogger::LEVEL_ERROR);
                        }
                        $pageWidget = new PageWidget;
                        $pageWidget->page_id = $model->id;
                        $pageWidget->revision_id = 1;
                        $pageWidget->content_type_id = 1;
                        $pageWidget->widget_id = $markup->id;
                        $pageWidget->widget_settings = var_export(array(
                            'data'=>array(
                                'condition'=>'id=:id',
                                'params'=>array(':id'=>$text->id),
                            ),
                        ),true);
                        $pageWidget->container = 'data';
                        $pageWidget->status = true;
                        $pageWidget->creation_datetime = date('Y-m-d H:i:s');
                        $pageWidget->last_update = date('Y-m-d H:i:s');
                        if (!$pageWidget->save())
                        {
                            Yii::log(CVarDumper::dumpAsString($pageWidget->getErrors()), CLogger::LEVEL_ERROR);
                        }
                    }
                    $url = $this->createUrl('/Cms/admin/page/update', array('id' => $model->id));
                    if (isset($_POST['task']) && $_POST['task'] == 'edit')
                    {
                        $pageRevision = $model->revisions(array('limit'=>1));
                        if (is_object($model->defaultUrl) && is_array($pageRevision) && is_object($pageRevision[0]))
                            $url = "http://".trim($pageRevision[0]->initialWorkflowUrl, "/")."/".trim($model->defaultUrl->url, "/")."/";
                    }
                    
                    $this->redirect($url);
                }
		}
            }
            else
            {
                if (Yii::app()->request->getIsAjaxRequest())
                {
                    echo CJSON::encode(array('error' => $result->getErrors()));
                    Yii::app()->end();
                }
                $pageRevision = new PageRevision();
                $pageRevision->attributes = $_POST['PageRevision'];
            }
        } else {
            // show edit form
            $id = $this->get('id', 0);
            $siteId = Yii::app()->cmsManager->site['id'];
            if ($id == 0) {
                $model = new Page();
                $model->site_id = $siteId;
                $model->parent_id = $this->get('parent_id', 0);
                $pageRevision = new PageRevision();
                $pageRevision->js_files = array('');
                $pageRevision->css_files = array('');
            } else {
                $model = FSM::run('Cms.Page.get', array('id' => $id))->model;
                if ($model->site_id != $siteId)
                    $this->redirect(array('admin'));
            }
        }
        
        if (is_object($pageRevision))
        {
            if (!is_array($pageRevision->css_files) || (is_array($pageRevision->css_files) && count($pageRevision->css_files) == 0))
                $pageRevision->css_files = array('');
            if (!is_array($pageRevision->js_files) || (is_array($pageRevision->js_files) && count($pageRevision->js_files) == 0))
                $pageRevision->js_files = array('');
        }
        
        if (!is_array($pageUrls) || (is_array($pageUrls) && count($pageUrls) <= 0))
            $pageUrls = array(new PageUrl());
            
        $defaultSiteId = Yii::app()->cmsManager->site['id'];
        $sites = FSM::run('Cms.site.getList')->models;
        if (count($sites))
        {
            $sites = CHtml::listData($sites, 'id', 'name');
            if (isset($sites[$defaultSiteId]))
                unset($sites[$defaultSiteId]);
        }
        
        if (Yii::app()->request->getQuery('layout', '') === 'popup')
        {
            if (Yii::app()->request->getIsAjaxRequest())
            {
                Yii::app()->theme = 'new_admin';
                $html = $this->renderPartial('details_ajax',array(
                    'model'=>$model, 
                    'pageUrls'=>$pageUrls, 
                    'pageRevision'=>$pageRevision,
                ), true, true);
                $html = preg_replace('/<script type="text\/javascript" src="([^"]+)jquery\.js"><\/script>/', '', $html);
                echo $html;
            }
            else
            {
                $this->render('details',array(
                    'model'=>$model, 
                    'pageUrls'=>$pageUrls, 
                    'pageRevision'=>$pageRevision,
                ));
            }
        }
        else
        {
            $this->render('update', array(
                'model' => $model,
                'pageUrls' => $pageUrls,
                'pageRevision' => $pageRevision,
                'sites' => $sites,
            ));
        }
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete()
    {
        if(Yii::app()->request->isPostRequest)
        {
            // we only allow deletion via POST request
            if (($ids = Yii::app()->request->getParam('ids', null)) !== null) {
                $deleteData = Yii::app()->request->getParam('delete_data', false);
                // delete one or multiple objects given the list of object IDs
                $result = FSM::run('Cms.Page.delete', array('ids' => $ids, 'delete_data'=>$deleteData));
                if ($result->hasErrors()) {
                    echo $result->getError('ErrorCode');
                } elseif(!Yii::app()->request->isAjaxRequest) {
                    // only redirect user to the admin page if it is not an AJAX request
                    $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
                }
            } else {
                throw new CHttpException(400,Yii::t('Core','Cannot delete item with the given ID.'));
            }
        } else {
            throw new CHttpException(400,Yii::t('Core','Invalid request. Please do not repeat this request again.'));
        }
    }

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDeleteUrl()
	{
        if(Yii::app()->request->isPostRequest)
        {
            // we only allow deletion via POST request
            if (($ids = Yii::app()->request->getParam('ids', null)) !== null) {
                $result = FSM::run('Cms.PageUrl.delete', array('ids' => $ids));
                if ($result->hasErrors()) {
                    echo $result->getError('ErrorCode');
                } elseif(!Yii::app()->request->isAjaxRequest) {
                    // only redirect user to the admin page if it is not an AJAX request
                    $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
                }
            } else {
                throw new CHttpException(400,Yii::t('Core','Cannot delete item with the given ID.'));
            }
        } else {
            throw new CHttpException(400,Yii::t('Core','Invalid request. Please do not repeat this request again.'));
        }
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
        $this->actionAdmin();
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
        $model=new Page('search');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['Page']))
            $model->attributes=$_GET['Page'];
        
        $criteria=new CDbCriteria;
        $defaultSiteId = Yii::app()->cmsManager->site['id'];
        $criteria->compare('site_id', $defaultSiteId);
        $criteria->compare('parent_id', 0);
        $criteria->order = 'ordering';
        $models = Page::model()->findAll($criteria);
            
        $sites = FSM::run('Cms.site.getList')->models;
        if (count($sites))
        {
            $sites = CHtml::listData($sites, 'id', 'name');
            if (isset($sites[$defaultSiteId]))
                unset($sites[$defaultSiteId]);
        }
        
        $result = FSM::_run('Cms.workflow.getBySite', array('site_id'=>$defaultSiteId));
        if (! $result->hasErrors())
        {
            $workflows = CHtml::listData($result->models, 'id', 'name');
            $result = FSM::_run('Cms.workflow.lookup');
            if (! $result->hasErrors())
            {
                if (isset($workflows[$result->model->id]))
                {
                    unset($workflows[$result->model->id]);
                }
            }
        }
        else
            $workflows = array();
        
        $this->render('admin', array('models'=>$models, 'sites'=>$sites, 'workflows'=>$workflows));
	}

    /**
     * Manages all models.
     */
    public function actionAdminFlat()
    {
        $model=new Page('search');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['Page']))
            $model->attributes=$_GET['Page'];
        
        $model->site_id = Yii::app()->cmsManager->site['id'];
            
        $sites = FSM::run('Cms.site.getList')->models;
        if (count($sites))
        {
            $sites = CHtml::listData($sites, 'id', 'name');
            if (isset($sites[$model->site_id]))
                unset($sites[$model->site_id]);
        }

        $this->render('admin-flat',array(
            'model'=>$model,
            'sites'=>$sites,
        ));
    }
    
    public function actionUrl($page_id)
    {
        $model=new PageUrl('search');
        $model->unsetAttributes();  // clear any default values
        $model->page_id = $page_id;
        if(isset($_GET['PageUrl']))
            $model->attributes=$_GET['PageUrl'];

        if (Yii::app()->request->getQuery('layout', '') === 'popup')
        {
            $this->render('/admin/pageUrl/admin',array(
                'model'=>$model,
                'pageId'=>$page_id,
            ));
        }
        else
        {
            $html = $this->renderPartial('/admin/pageUrl/admin',array(
                'model'=>$model,
                'pageId'=>$page_id,
            ), true, true);
            $html = preg_replace('/<link rel="stylesheet" type="text\/css" href="([^"]+)\.css" \/>/', '', $html);
            $html = preg_replace('/<script type="text\/javascript" src="([^"]+)\.js"><\/script>/', '', $html);
            echo $html;
        }
    }
    
    public function actionAddUrl($page_id)
    {
        $this->actionUpdateUrl($page_id);
    }
    
    public function actionUpdateUrl($page_id)
    {
        if (Yii::app()->request->IsPostRequest) {
            // save posted data
            $_POST['validateOnly'] = ($this->post('ajax','') == 'pageUrl-form');
            $result = FSM::run('Cms.PageUrl.save', $_POST);
            $model = $result->model;

            if ($this->post('ajax','') == 'pageUrl-form'){
                echo $result->getActiveErrorMessages($result->model);
                Yii::app()->end();
            }   
            if ($result->hasErrors()) {
                $script = "parent.\$.fancyboxResize(\$('body').height()+50);";
                Yii::app()->clientScript->registerScript(__CLASS__.'#FancyboxResize', $script, CClientScript::POS_READY);
            } else {
                //$this->message = Yii::t('Core','Item has been saved successfully.');
                $script = "parent.\$.reloadPageUrlTab();parent.\$.fancybox.close();";
                Yii::app()->clientScript->registerScript(__CLASS__.'#ReloadPageUrl', $script, CClientScript::POS_READY);
            }
        } else {
            // show edit form
            $id = $this->get('id', 0);
            if ($id == 0) {
                $model = new PageUrl();
            } else {
                $model = FSM::run('Cms.PageUrl.get', array('id' => $id))->model;
            }
            $model->page_id = $page_id;
        }
        if (Yii::app()->request->getQuery('layout', '') === 'popup')
        {
            $this->render('/admin/pageUrl/update', array('model' => $model));
        }
        else
        {
            $this->renderPartial('/admin/pageUrl/update', array('model' => $model), false, true);
        }
    }
    
    public function actionStatusUrl()
    {
        $result = FSM::run('Cms.PageUrl.changeStatus', $_GET);
        if ($result->hasErrors()) {
            echo $result->getError('ErrorCode');
        } elseif(!Yii::app()->request->isAjaxRequest) {
            // only redirect user to the admin page if it is not an AJAX request
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
    }
    
    public function actionSetDefaultUrl($id)
    {
        $result = FSM::run('Cms.PageUrl.setDefault', $_GET);
        echo $result->toJson();
    }
    
    public function actionTree()
    {
        $model=new Page('search');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['Page']))
            $model->attributes=$_GET['Page'];
        
        $criteria=new CDbCriteria;
        
        $workflowId = 0;
        $siteId = 0;
        $result = FSM::run('Cms.Workflow.lookup');
        if (!$result->hasErrors())
        {
            $workflowId = $result->model->id;
            $siteId = $result->model->site_id;
        }
        
        //find active pages in workflow
        $command = Yii::app()->db->createCommand();
        $this->_activePages = $command->select('*')
            ->from(SITE_TABLE_PREFIX.'page_current_revision')
            ->where('workflow_id=:workflow_id', array(':workflow_id'=>$workflowId))
            ->queryColumn();
        
        $criteria->compare('site_id', $siteId);
        $criteria->compare('parent_id', 0);
        $criteria->order = 'ordering';
        $models = Page::model()->findAll($criteria);
        
        Yii::app()->theme = 'new_admin';
        $this->render('tree', array('models'=>$models));
    }
    
    public function actionMasterContent()
    {
        $model=new Page('search');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['Page']))
            $model->attributes=$_GET['Page'];
        
        $criteria=new CDbCriteria;
        
        $workflowId = 0;
        $siteId = 0;
        $result = FSM::run('Cms.Workflow.lookup');
        if (!$result->hasErrors())
        {
            $workflowId = $result->model->id;
            $siteId = $result->model->site_id;
        }
        
        $criteria->compare('site_id', $siteId);
        $criteria->compare('parent_id', 0);
        $criteria->order = 'ordering';
        $models = Page::model()->findAll($criteria);
        
        $workflows = Workflow::model()->findAllByAttributes(array('site_id'=>$siteId));
        if (is_array($workflows) && count($workflows))
        {
            $tmp = array();
            foreach ($workflows as $workflow)
            {
                $tmp[$workflow->id] = $workflow->name.'('.$workflow->url.')';
            }
            $workflows = $tmp;
        }
        $this->render('master_content', array('models'=>$models,'workflows'=>$workflows, 'workflowId'=>$workflowId));
    }
    
    protected function renderNestedPage($models)
    {
        $count = count($models);
        foreach ($models as $index => $model) {
            $children = $model->children;
            $childrenCount = 0;
            if (is_array($children))
                $childrenCount = count($children);
            $class = 'sortable';
            if ($index == 0) $class .= ' first';
            if ($index == $count-1) $class .= ' last';
            echo '<li class="'.$class.'" id="items-'.$model->id.'">';
            $this->renderPartial('_item', array('model'=>$model, 'isActive'=>in_array($model->id, $this->_activePages), 'hasChild'=>(boolean) $childrenCount));
            if ($childrenCount)
            {
                echo '<ul>';
                $this->renderNestedPage($children);
                echo '</ul>';
            }
            echo '</li>';
        }
    }
    
    protected function renderAdminNestedPage($viewFile, $models)
    {
        foreach ($models as $index => $model) {
            $children = $model->children;
            $childrenCount = 0;
            if (is_array($children))
                $childrenCount = count($children);
            echo '<li class="sortable" id="items-'.$model->id.'">';
            Yii::app()->controller->renderFile($viewFile, array('class'=>'odd', 'model'=>$model, 'hasChild'=>(boolean) $childrenCount));
            
            if ($childrenCount)
            {
                echo '<ul>';
                $this->renderAdminNestedPage($viewFile, $children);
                echo '</ul>';
            }
            echo '</li>';
        }
    }
    
    public function actionCopyRevision($page_id, $revision)
    {
        $result = FSM::run('Cms.Workflow.lookup');
        $isInitialWorkflow = false;
        $siteId = 0;
        if (!$result->hasErrors())
        {
            $siteId = $result->model->site_id;
            $isInitialWorkflow = $result->model->type == Workflow::TYPE_INITITAL;
        }
        $sites = FSM::run('Cms.site.getList')->models;
        if (count($sites))
        {
            $sites = CHtml::listData($sites, 'id', 'name');
            if (isset($sites[$siteId]))
                unset($sites[$siteId]);
        }
        
        $model = Page::model()->findByPk($page_id);
        $pageInfo = 'Copy page '.$model->title.'#rev'.$revision;
        
        //show copy button
        $script = "setTimeout(function(){\$('input[type=\"submit\"]').closest('.row').show();}, 500);";
        Yii::app()->clientScript->registerScript('ShowSaveButton', $script);
        $this->render('_form_copy', array(
            'sites'=>$sites,
            'pageId'=>$page_id,
            'revision'=>$revision,
            'siteId'=>$siteId,
            'pageInfo'=>$pageInfo,
        ));
    }
    
    public function actionValidateUrl()
    {
        if(isset($_POST['PageUrl']))
        {
            Yii::trace(CVarDumper::dumpAsString($_POST['PageUrl']), 'PageUrl');
            $items = array();
            foreach($_POST['PageUrl'] as $i => $value)
            {
                $model = new PageUrl;
                if(isset($_POST['PageUrl'][$i]))
                    $model->attributes=$_POST['PageUrl'][$i];
                $model->validate();
                $items[$i] = $model->getErrors();
            }
            echo CJSON::encode($items);
            Yii::app()->end();
        }
    }

    /**
     * Compare pages between 2 workflows
     * 
     * @param target_id int required, target workflow to compare
     * @param source_id int optional, target workflow to compare
     */
    public function actionCompare()
    {
        $sourceId = $this->get('source_id', 0);
        $targetId = $this->get('target_id', 0);
        if ($sourceId == 0)
        {
            $result = FSM::_run('Cms.workflow.lookup');
            if (!$result->hasErrors())
            {
                $source = $result->model;
            }
            else
            {
                throw new CException('Oups, Not detect workflow source.');
            }
        }
        else
        {
            $source = Workflow::model()->findByPk($sourceId);
        }
        
        if (! is_object($source))
        {
            throw new CException('Oups, not found source workflow.');
        }
        
        $target = Workflow::model()->findByPk($targetId);
        if (! is_object($target))
        {
            throw new CException('Oups, target workflow is required to compare.');
        }
        elseif ($source->id == $target->id)
        {
            throw new CException('Oups, compare same workflow.');
        }
        
        $criteria=new CDbCriteria;
        $criteria->select = array('id', 'title');
        $criteria->with = array(
            'currentRevisions'=>array(
                'together'=>true,
                'index'=>'workflow_id',
                'condition'=>'workflow_id = :source_workflow_id OR workflow_id = :target_workflow_id',
                'params'=>array(':source_workflow_id'=>$source->id, ':target_workflow_id'=>$target->id),
            ),
        );
        $defaultSiteId = Yii::app()->cmsManager->site['id'];
        $criteria->compare('site_id', $defaultSiteId);
        $criteria->compare('parent_id', 0);
        $criteria->order = 'ordering';
        $models = Page::model()->findAll($criteria);
        
        $this->render('compare', array(
            'models'=>$models,
            'source'=>$source,
            'target'=>$target
        ));
    }
    
    protected function renderCompareNestedPage($viewFile, $models, $sourceId, $targetId)
    {
        foreach ($models as $index => $model) {
            echo '<li class="sortable" id="items-'.$model->id.'">';
            //Yii::trace('Item '.$model->id.': '.CVarDumper::dumpAsString($model->currentRevisions), 'Compare');
            Yii::app()->controller->renderFile($viewFile, array('class'=>'odd', 'model'=>$model, 'sourceId'=>$sourceId, 'targetId'=>$targetId));
            $children = $model->children(array(
                'select'=>array('id', 'title'),
                'with'=>array(
                    'currentRevisions'=>array(
                        'together'=>true,
                        'index'=>'workflow_id',
                        'condition'=>'workflow_id = :source_workflow_id OR workflow_id = :target_workflow_id',
                        'params'=>array(':source_workflow_id'=>$sourceId, ':target_workflow_id'=>$targetId),
                    ),
                )
            ));
            if (is_array($children) && count($children)) {
                echo '<ul>';
                $this->renderCompareNestedPage($viewFile, $children, $sourceId, $targetId);
                echo '</ul>';
            }
            echo '</li>';
        }
    }
    
    public function actionCompareDetails()
    {
        $pageId = $this->get('page_id', 0);
        $sourceRevision = $this->get('source_revision', 0);
        $targetRevision = $this->get('target_revision', 0);
        $sourceId = $this->get('source_workflow_id', 0);
        $targetId = $this->get('target_workflow_id', 0);
        
        /*$source = $this->getPageDetails($pageId, $sourceRevision, $sourceId);
        $target = $this->getPageDetails($pageId, $targetRevision, $targetId);*/
        $source = FSM::run('Cms.page.getPageDetails', array('page_id'=>$pageId, 'revision'=>$sourceRevision, 'workflow_id'=>$sourceId))->model;
        $target = FSM::run('Cms.page.getPageDetails', array('page_id'=>$pageId, 'revision'=>$targetRevision, 'workflow_id'=>$targetId))->model;

        $sourceWorkflow = Workflow::model()->findByPk($sourceId);
        $targetWorkflow = Workflow::model()->findByPk($targetId);
        
        $containers = array();
        foreach ($source->pageWidgets as $item)
        {
            if (isset($containers[$item->container]))
            {
                if (isset($containers[$item->container]['source']))
                    $containers[$item->container]['source'][] = $item;
                else
                    $containers[$item->container]['source'] = array($item);
            }
            else
            {
                $containers[$item->container] = array('source'=>array($item));
            }
        }
        foreach ($target->pageWidgets as $item)
        {
            if (isset($containers[$item->container]))
            {
                if (isset($containers[$item->container]['target']))
                    $containers[$item->container]['target'][] = $item;
                else
                    $containers[$item->container]['target'] = array($item);
            }
            else
            {
                $containers[$item->container] = array('target'=>array($item));
            }
        }
        
        $sourceTemplate = $source->revisions[0]->templateContent->template->name.' #'.$source->revisions[0]->templateContent->revision_id;
        $targetTemplate = $target->revisions[0]->templateContent->template->name.' #'.$target->revisions[0]->templateContent->revision_id;
        
        $this->render('compare_details', array(
            'pageTitle'=>$source->title,
            'containers'=>$containers,
            'sourceWorkflow'=>$sourceWorkflow->name,
            'targetWorkflow'=>$targetWorkflow->name,
            'sourceTemplate'=>$sourceTemplate,
            'targetTemplate'=>$targetTemplate,
        ));
    }
    
    public function actionEditLog()
    {
        $id = $this->get('id', 0);
        $data = $this->post('data', '');
        
        Page::model()->updateByPk($id, array(
            'note'=>$data,
            'last_update'=>date('Y-m-d H:i:s'),
        ));
    }
    
    public function actionExport()
    {       
        $selectedWorkFlowId = '';
        if (Yii::app()->request->isPostRequest && isset($_POST['workflowId']) && isset($_POST['pageIds']))
        {
            $selectedWorkFlowId = $_POST['workflowId'];
            
            $pages = array();
            $pageIds = explode(',',$_POST['pageIds']);
            
            // export to EXCEL file
            Yii::import('application.vendors.phpexcel176.PHPExcel');
            //Yii::import('application.vendors.phpExcel.PHPExcel.Shared.*');
            //include('/protected/vendors/phpExcel/PHPExcel.php');
            //require_once '/protected/vendors/phpexcel167/PHPExcel.php';
            $phpExcelObj = new PHPExcel();
            $phpExcelObj->getProperties()->setCreator("Kodo Admin");
            $phpExcelObj->getProperties()->setLastModifiedBy("Kodo Admin");
            $phpExcelObj->getProperties()->setTitle("Pages and widget content");
            $phpExcelObj->getProperties()->setSubject("Pages and widget content");
            $phpExcelObj->getProperties()->setDescription("Pages and widget content");
            
            $phpExcelObj->setActiveSheetIndex(0);
            $phpExcelObj->getActiveSheet()->setTitle('CMS content');
            $phpExcelObj->getActiveSheet()->getColumnDimension('D')->setWidth(50);
            $phpExcelObj->getActiveSheet()->SetCellValue('A1', 'Page Title');
            $phpExcelObj->getActiveSheet()->SetCellValue('B1', 'Page Alias');
            $phpExcelObj->getActiveSheet()->SetCellValue('C1', 'Notes');
            $phpExcelObj->getActiveSheet()->SetCellValue('E1', 'Text only');
            $phpExcelObj->getActiveSheet()->SetCellValue('F1', 'Translation');
            
            $start = 2;
            
            foreach($pageIds as $pageId)
            {
                $page = Page::model()->findByPk($pageId);
                if (is_null($page)) continue;
                $pages[] = $page;
                // set columns value
                $phpExcelObj->getActiveSheet()->SetCellValue('A'.$start, $page->title);
                $phpExcelObj->getActiveSheet()->SetCellValue('B'.$start, $page->alias);
                $phpExcelObj->getActiveSheet()->SetCellValue('C'.$start, $page->note);
                //$phpExcelObj->getActiveSheet()->SetCellValue('E'.$start, 'Text only');
                //$phpExcelObj->getActiveSheet()->SetCellValue('F'.$start, 'User Entered Content');
                $start++;
                
                // find revision_id of selected workflow
                $pageCurrentRev = PageCurrentRevision::model()->find('page_id=:pageId AND workflow_id=:workflowId',array(':pageId'=>$page->id,':workflowId'=>$selectedWorkFlowId));
                if (is_null($pageCurrentRev))
                {
                    $start++;
                    continue;
                }
                // find all widgets added into the page
                $criteria = new CDbCriteria();
                $criteria->with = array('widget');
                $criteria->compare('t.page_id',$page->id);
                $criteria->compare('t.revision_id',$pageCurrentRev->revision);
                $criteria->addCondition('t.status = true');
                $criteria->addCondition('t.exported = true');
                $criteria->addInCondition('widget.path',array('Cms/widgets/pureHtml','Cms/widgets/richText','Cms/widgets/markupCode'));    
                $criteria->order = ' t.id ASC';
                $pageWidgets = PageWidget::model()->findAll($criteria);
                foreach($pageWidgets as $pageWidget)
                {
                    $phpExcelObj->getActiveSheet()->SetCellValue('B'.$start, $pageWidget->id);
                    $phpExcelObj->getActiveSheet()->SetCellValue('C'.$start, $pageWidget->widget->name);
                    if (empty($pageWidget->widget_settings)) $pageWidget->widget_settings = "''";
                    eval('$settings ='.$pageWidget->widget_settings.';');
                    if (!is_array($settings) || !isset($settings['widget']) || !is_array($settings['widget']) || !isset($settings['widget']['id'])) continue;
                    $textObj = Text::model()->findByPk($settings['widget']['id']);
                    $widget_content = '';
                    if (!is_null($textObj)) $widget_content = trim($textObj->content);
                    $phpExcelObj->getActiveSheet()->SetCellValue('D'.$start, $widget_content); 
                    // strip tags in content
                    $widget_simple_content = strip_tags($widget_content);
                    $widget_simple_content = trim(html_entity_decode($widget_simple_content,ENT_COMPAT,'UTF-8'));
                    $phpExcelObj->getActiveSheet()->SetCellValue('E'.$start, $widget_simple_content);
                    $start++;
                }
                $start++;
            }
            
            // sheet 2
            $phpExcelObj->createSheet(1);
            $phpExcelObj->setActiveSheetIndex(1);
            $phpExcelObj->getActiveSheet()->setTitle('Email Subjects');
            $phpExcelObj->getActiveSheet()->getColumnDimension('B')->setWidth(50);
            $phpExcelObj->getActiveSheet()->SetCellValue('A1', 'Id');
            $phpExcelObj->getActiveSheet()->SetCellValue('B1', 'Subject');
            $phpExcelObj->getActiveSheet()->SetCellValue('C1', 'Translated');
            // in sheet 2, get all terms with vocabulary email subjects
            $emailSubVoc = Vocabulary::model()->find('alias=:alias AND module=:module',array(':alias'=>'email-subjects',':module'=>'Site'));
            if (!is_null($emailSubVoc))
            {
                $emailSubTerms = Term::model()->findAll('v_id=:vocId AND state=:state',array(':vocId'=>$emailSubVoc->id,':state'=>Term::STATE_ACTIVE));
                $start = 2;
                foreach($emailSubTerms as $term)
                {
                    $phpExcelObj->getActiveSheet()->SetCellValue('A'.$start, $term->id);
                    $phpExcelObj->getActiveSheet()->SetCellValue('B'.$start, $term->description);
                    $start++;    
                }
            }
            
            // sheet 3, get content of metadata widget on each page
            $phpExcelObj->createSheet(2);
            $phpExcelObj->setActiveSheetIndex(2);
            $phpExcelObj->getActiveSheet()->setTitle('Metadata widgets content');
            $phpExcelObj->getActiveSheet()->getColumnDimension('D')->setWidth(50);
            $phpExcelObj->getActiveSheet()->SetCellValue('A1', 'Page Title');
            $phpExcelObj->getActiveSheet()->SetCellValue('B1', 'Page Alias');
            $phpExcelObj->getActiveSheet()->SetCellValue('C1', 'Notes');
            $phpExcelObj->getActiveSheet()->SetCellValue('E1', 'Translation');
            $start = 2;
            foreach($pages as $page)
            {
                // find revision_id of selected workflow
                $pageCurrentRev = PageCurrentRevision::model()->find('page_id=:pageId AND workflow_id=:workflowId',array(':pageId'=>$page->id,':workflowId'=>$selectedWorkFlowId));
                if (is_null($pageCurrentRev))
                    continue;
                // find all widgets added into the page
                $criteria = new CDbCriteria();
                $criteria->with = array('widget');
                $criteria->compare('t.page_id',$page->id);
                $criteria->compare('t.revision_id',$pageCurrentRev->revision);
                $criteria->addCondition('t.status = true');
                $criteria->addCondition('t.exported = true');
                $criteria->addInCondition('widget.path',array('Cms/widgets/metadata','Cms/widgets/facebookTag','Cms/widgets/pinterest'));    
                $criteria->order = ' t.id ASC';
                $pageWidgets = PageWidget::model()->findAll($criteria);
                if (count($pageWidgets) <= 0)
                    continue;
                // set columns value
                $phpExcelObj->getActiveSheet()->SetCellValue('A'.$start, $page->title);
                $phpExcelObj->getActiveSheet()->SetCellValue('B'.$start, $page->alias);
                $phpExcelObj->getActiveSheet()->SetCellValue('C'.$start, $page->note);
                //$phpExcelObj->getActiveSheet()->SetCellValue('E'.$start, 'User Entered Content');
                $start++;
                foreach($pageWidgets as $pageWidget)
                {
                    $phpExcelObj->getActiveSheet()->SetCellValue('B'.$start, $pageWidget->id);
                    $phpExcelObj->getActiveSheet()->SetCellValue('C'.$start, $pageWidget->widget->name);
                    if (empty($pageWidget->widget_settings)) $pageWidget->widget_settings = "''";
                    eval('$settings ='.$pageWidget->widget_settings.';');
                    if (!is_array($settings) || !isset($settings['widget']) || !is_array($settings['widget']) || !isset($settings['widget']['id'])) continue;
                    // if this widget is Cms/widgets/metadata
                    if ($pageWidget->widget->path == 'Cms/widgets/metadata')
                    {
                        $metadataObj = Metadata::model()->findByPk($settings['widget']['id']);
                        $widget_content = '';
                        if (!is_null($metadataObj))
                        {
                            $widget_content = '1. Title'."\n".trim($metadataObj->title)."\n"
                            .'2. Keywords'."\n".trim($metadataObj->keywords)."\n"
                            .'3. Description'."\n".trim($metadataObj->description);
                            $phpExcelObj->getActiveSheet()->SetCellValue('D'.$start, $widget_content);
                        }        
                    }
                    elseif ($pageWidget->widget->path == 'Cms/widgets/facebookTag')
                    {
                        $fbmetadataObj = FbMetadata::model()->findByPk($settings['widget']['id']);
                        $widget_content = '';
                        if (!is_null($fbmetadataObj))
                        {
                            $widget_content = '1. Title'."\n".trim($fbmetadataObj->title)."\n"
                            .'2. URL'."\n".trim($fbmetadataObj->url)."\n"
                            .'3. Type'."\n".trim($fbmetadataObj->type)."\n"
                            .'4. Image'."\n".trim($fbmetadataObj->image)."\n"
                            .'5. Site Name'."\n".trim($fbmetadataObj->site_name)."\n"
                            .'6. Description'."\n".trim($fbmetadataObj->description);
                            $phpExcelObj->getActiveSheet()->SetCellValue('D'.$start, $widget_content);
                        }    
                    }
                    else
                    {
                        $pinImg = '';
                        $pinUrl = '';
                        $pinDesc = '';
                        if (isset($settings['widget']['image'])) $pinImg = trim($settings['widget']['image']);
                        if (isset($settings['widget']['url'])) $pinUrl = trim($settings['widget']['url']);
                        if (isset($settings['widget']['description'])) $pinDesc = trim($settings['widget']['description']);
                        $widget_content = '1. Image'."\n".$pinImg."\n"
                        .'2. URL'."\n".$pinUrl."\n"
                        .'3. Description'."\n".$pinDesc;
                        $phpExcelObj->getActiveSheet()->SetCellValue('D'.$start, $widget_content);   
                    }
                    $start++;
                }
                $start++;
            }
            
            // back to sheet 1
            $phpExcelObj->setActiveSheetIndex(0);
            
            //var_dump($pagesData);
            // Save Excel 2003 file
            //header("Pragma: public"); // required
            //header("Expires: 0");
            //header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
            //header("Cache-Control: private",false); // required for certain browsers
            /*header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="classnameg.xls"');
            header('Cache-Control: max-age=0');*/
            //header("Content-Transfer-Encoding: binary");
            $objWriter = PHPExcel_IOFactory::createWriter($phpExcelObj, 'Excel5');
            //objWriter->save('php://output');
            //$file = str_replace('.php', '.xls', __FILE__);
            $domain = parse_url(Yii::app()->request->getHostInfo(), PHP_URL_HOST);
            $selectedWorkFlow = Workflow::model()->findByPk($selectedWorkFlowId);
            if (!is_null($selectedWorkFlow))
                $workFlowName = $selectedWorkFlow->name;
            else
                $workFlowName = $selectedWorkFlowId;
            $filename = $domain.'_'.str_replace(array('_',' ','/'),'-',$workFlowName).'_'.date('m-d-Y');
            $file = Yii::getPathOfAlias('site').'/../uploads/'.$filename.'.xls';
            $objWriter->save($file);
            //Yii::app()->request->sendFile($file,file_get_contents($file),'application/vnd.ms-excel');
            $url = str_replace("\\",'/',Yii::app()->request->getHostInfo().'/sites/'.SITE_DIR.'/uploads/'.$filename.'.xls');
            echo '<a href="'.$url.'">Download Excel file</a>';
            $this->redirect($url);
            //header('Location : '.$url);
            //exit;
        }
        else
        {
            $app = Yii::app();
            $defaultHost = parse_url($app->request->hostInfo, PHP_URL_HOST);
            $pathInfo = $app->request->getPathInfo();                
            $locale = substr($pathInfo,0,5);
            $localeId = str_replace('/','_',$locale);
            if ($app->localeManager->isLocaleIdValid($localeId))
                $defaultHost = $defaultHost.'/'.$locale;
            // find the workflow from URI host info
            $result = FSM::_run('Cms.workflow.getByUrl', array('url'=>$defaultHost));
            if (!$result->hasErrors() && !is_null($result->model))
                $selectedWorkFlowId = $result->model->id;
        }
        $this->render('export',array('selectedWorkFlowId'=>$selectedWorkFlowId));
    }
    
    public function actionPagesByWorkflow()
    {
        $workflow_id = $this->get('workflow_id','');
        
        $model=new Page('searchByWorkflow');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['Page']))
            $model->attributes=$_GET['Page'];
            
        $model->selectedWorkflowId = (int) $workflow_id;
        
        $html = $this->renderPartial('_pages_by_workflow',array(
            'model'=>$model,
        ), true, true);
        //don't load scripts
        $html = preg_replace('/<link rel="stylesheet" type="text\/css" href="([^"]+)\.css" \/>/', '', $html);
        $html = preg_replace('/<script type="text\/javascript" src="([^"]+)\.js"><\/script>/', '', $html);
        echo $html;    
    }
    
    public function actionWidgets()
    {
        if (Yii::app()->request->getIsPutRequest())
        {
            $data = Yii::app()->request->getPut('model', '');
            if (!empty($data))
            {
                $data = CJSON::decode($data);
                $pageWidget = PageWidget::model()->findByPk($data['id']);
                if (is_object($pageWidget))
                {
                    $pageWidget->saveAttributes(array('exported'=>(boolean) $data['exported']));
                    $modelClass = Yii::import($pageWidget->contentType->model);
                    $settings = $this->evaluateExpression($pageWidget->widget_settings);
                    $model = PageWidget::model($modelClass)->findByPk($settings['widget']['id']);
                    if ($data['type'] === 'image')
                        $model->saveAttributes(array('source'=>$data['content']));
                    else
                        $model->saveAttributes(array('content'=>$data['content']));
                }
            }
            Yii::app()->end();
        }
        $pageId = $this->get('page_id');
        $workflowId = $this->get('workflow_id');
        $widgets = FSM::_run('Cms.page.getWidgets', array(
            'page_id'=>$pageId,
            'workflow_id'=>$workflowId,
        ))->widgets;
        if ($widgets === false)
            $widgets = $this->createAbsoluteUrl('/Cms/admin/workflow/page',array('page_id'=>$pageId,'workflow_id'=>$workflowId,'layout'=>'popup'));
        echo CJSON::encode($widgets);
    }
}
